﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RayTracing
{
    public class ImageTexture : Texture
    {
        System.Drawing.Bitmap textureMap;

        float xMin = 0;
        float xMax = 1;
        float yMin = 0;
        float yMax = 1;
        Color color = Color.BLACK;


        public ImageTexture(System.Drawing.Image image)                 // Constructor takes any sceneImage and turns it into a bitmap.
        {
            this.textureMap = new System.Drawing.Bitmap(image);
        }

        public ImageTexture(System.Drawing.Image image, float xMin, float xMax, float yMin, float yMax)                 // Constructor takes any sceneImage and turns it into a bitmap.
        {
            this.textureMap = new System.Drawing.Bitmap(image);
            this.xMin = xMin;
            this.xMax = xMax;
            this.yMin = yMin;
            this.yMax = yMax;
        }

        public ImageTexture(System.Drawing.Image image, float xMin, float xMax, float yMin, float yMax, Color color)                 // Constructor takes any sceneImage and turns it into a bitmap.
        {
            this.textureMap = new System.Drawing.Bitmap(image);
            this.xMin = xMin;
            this.xMax = xMax;
            this.yMin = yMin;
            this.yMax = yMax;
            this.color = color;
        }


        #region Texture Members
                                                                
        public Color textureAt(P2 p)                            // takes a P2 p and returns the color of the texture at the 
        {
                                                                // the location p. (dark magic math)
            float x = p.x * (xMax - xMin)+xMin;
            float y = p.y * (yMax - yMin)+yMin;
            
            int pX = (int)(x * textureMap.Width);
            int pY = (int)(y * textureMap.Height);

            if (pX >= 0 && pX < textureMap.Width)
            {
                System.Drawing.Color c = textureMap.GetPixel(pX,pY);
                return new Color(c.R/256.0f,c.G/256.0f,c.B/256.0f);
            }
            return color;
            
        }

        #endregion
    }
}
